import 'package:flutter/material.dart';
import 'package:gridviewdemo/colors/colors.dart';
import 'package:gridviewdemo/models/models.dart';

/// {@template simple_puzzle_tile}
/// Displays the puzzle tile associated with [tile] and
/// the font size of [tileFontSize] based on the puzzle [state].
/// {@endtemplate}
@visibleForTesting
class SimplePuzzleTile extends StatefulWidget {
  /// {@macro simple_puzzle_tile}
  const SimplePuzzleTile({
    Key? key,
    required this.tile,
    required this.tileFontSize,
  }) : super(key: key);

  /// The tile to be displayed.
  final Tile tile;

  /// The font size of the tile to be displayed.
  final double tileFontSize;

  @override
  SimplePuzzleTileState createState() => SimplePuzzleTileState();

}

class SimplePuzzleTileState extends State<SimplePuzzleTile>
    with TickerProviderStateMixin {

  late final AnimationController showAnimController;
  late final AnimationController touchAnimController;

  late final Animation<double> height;
  late final Animation<double> scale;
  late final Animation<double> scaleBack;
  late final Animation<EdgeInsets> padding;
  late final Animation<Color?> color;

  var type = 1;
  var buttonStatus = 1;

  late WidgetsBinding widgetsBinding;

  @override
  void initState() {
    super.initState();

    showAnimController = AnimationController(
      duration: const Duration(milliseconds: 2000),
      vsync: this,
    );

    touchAnimController = AnimationController(
      duration: const Duration(milliseconds: 500),
      vsync: this,
    );

//    //高度动画
//    height = Tween<double>(
//      begin: .0,
//      end: 300.0,
//    ).animate(
//      CurvedAnimation(
//        parent: controller,
//        curve: const Interval(
//          0.0, 0.6, //间隔，前60%的动画时间
//          curve: Curves.ease,
//        ),
//      ),
//    );

    //高度动画
    scale = Tween<double>(
      begin: 0.3,
      end: 1.0,
    ).animate(
      CurvedAnimation(
        parent: showAnimController,
        curve: const Interval(
          0.0, 1.0,
          curve: Curves.elasticIn,
        ),
      ),
    );

    //高度动画
//    scaleBack = Tween<double>(
//      begin: 1.0,
//      end: 0.3,
//    ).animate(
//      CurvedAnimation(
//        parent: touchAnimController,
//        curve: const Interval(
//          0.0, 1.0,
//          curve: Curves.bounceIn,
//        ),
//      ),
//    );

    scaleBack = Tween(begin: 1.0, end: 0.5)
        .chain(CurveTween(curve: Curves.bounceIn))
        .animate(touchAnimController);

    scaleBack.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        //动画执行结束时反向执行动画
//        controller.reverse();

        buttonStatus = 1;


        setState(() {
          print("setState ${widget.tile}");
        });
      } else if (status == AnimationStatus.dismissed) {
        //动画恢复到初始状态时执行动画（正向）
//        controller.forward();
      }
    });

//    color = ColorTween(
//      begin: Colors.green,
//      end: Colors.red,
//    ).animate(
//      CurvedAnimation(
//        parent: controller,
//        curve: const Interval(
//          0.0, 0.6, //间隔，前60%的动画时间
//          curve: Curves.ease,
//        ),
//      ),
//    );
//
//    padding = Tween<EdgeInsets>(
//      begin: const EdgeInsets.only(left: .0),
//      end: const EdgeInsets.only(left: 100.0),
//    ).animate(
//      CurvedAnimation(
//        parent: controller,
//        curve: const Interval(
//          0.6, 1.0, //间隔，后40%的动画时间
//          curve: Curves.ease,
//        ),
//      ),
//    );

    widgetsBinding = WidgetsBinding.instance;
    widgetsBinding.addPostFrameCallback((callback){
      print("addPostFrameCallback be invoke");

      _playAnimation();
    });
  }

  _playAnimation() async {
    try {
      if (type == 1) {
        //先正向执行动画
        await showAnimController.forward().orCancel;
        //再反向执行动画
//      await controller.reverse().orCancel;
      }
      else {
        //先正向执行动画
        await touchAnimController.forward().orCancel;
        //再反向执行动画
        await touchAnimController.reverse().orCancel;
      }

    } on TickerCanceled {
      // the animation got canceled, probably because we were disposed
    }
  }

  @override
  Widget build(BuildContext context) {

    print("******* build ${widget.tile}");

    if (type == 1) {
      return AnimatedBuilder(
        builder: _buildAnimation,
        animation: showAnimController,
      );
    } else {
      return AnimatedBuilder(
        builder: _buildAnimation,
        animation: touchAnimController,
      );
    }

  }

  Widget _buildAnimation(BuildContext context, child) {

//    print("******* _buildAnimation ${widget.tile}");

    return Container(
      alignment: Alignment.bottomCenter,
//      padding: padding.value,
      child: contentView(context),
    );
  }

  Widget contentView(BuildContext context) {
//    final theme = context.select((ThemeBloc bloc) => bloc.state.theme);

    String imagePath = 'images/normal.png';

    if (buttonStatus == 2) {
      imagePath = 'images/showing.png';
    }

    return GestureDetector(
        onTap: () {
          print("点击了 ${widget.tile}");

          type = 2;
          buttonStatus = 2;

          setState(() {
            print("setState ${widget.tile}");

          });

          print("setState 结束${widget.tile}");

          _playAnimation();
        },
        child: imageBgButton(imagePath, widget.tile.value.toString(), () {
          print("点击了 ${widget.tile}");
        })
    );

  }

  Widget imageBgButton(String imgPath, String text, VoidCallback? onPressed,) {

    var scaleValue = type == 1 ? scale.value : scaleBack.value;

    return Container(
      width: 100 * scaleValue,
      height: 100 * scaleValue,
      decoration: BoxDecoration(
        color: Colors.transparent,
        image: DecorationImage(
            image: AssetImage(imgPath),
            fit: BoxFit.contain
        ),
      ),
      alignment: Alignment.center,
      child: Text(
          text,
        style: TextStyle(
              fontSize: 30 * scaleValue,
              color: const Color(0xffffffff),
              fontFamily: "Arial",
              fontWeight: FontWeight.w900),
      ),

    );
  }
}